//
//  EmoticonViewController.swift
//  FaceKeyBoard
//
//  Created by cmh on 15/9/12.
//  Copyright © 2015年 cmh. All rights reserved.
//

import UIKit

private let EmoticonViewCellID = "EmoticonViewCellID"

class EmoticonViewController: UIViewController {
    
    var selectedEmoticonCallBack: (emoticon: Emoticon) -> ()
    
    init (selectedEmoticon: (emoticon: Emoticon) -> ()) {
        selectedEmoticonCallBack = selectedEmoticon
        
        super.init(nibName: nil, bundle: nil)
    
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.redColor()
        
        viewModel.loadPackages()

        setupUI()
        
    }
    
    @objc private func clickBtn(item: UIBarButtonItem) {
    
        let index = NSIndexPath(forRow: 0, inSection: item.tag)
        
        collectionView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)

    }

    // 设置ui
    private func setupUI() {
        
        view.addSubview(collectionView)
        view.addSubview(toolbar)
        
        
        // 设置自动布局
        
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDict = ["tb": toolbar, "cv": collectionView]
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-[tb(44)]-0-|", options: [], metrics: nil, views: viewDict))
        
        prepareToolBar()
        prepareCollectionView()

    }
    
    // 准备toolbar视图
    private func prepareToolBar() {
        
        toolbar.tintColor = UIColor.darkGrayColor()
        
        var items = [UIBarButtonItem]()
        
        var index = 0
        
        for t in viewModel.packages {

            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            items.append(UIBarButtonItem(title: t.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "clickBtn:"))
            items.last?.tag = index++
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        toolbar.items = items
    }
    
    // 准备collectionview视图
    private func prepareCollectionView() {
        
        collectionView.backgroundColor = UIColor.whiteColor()
        
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: EmoticonViewCellID)
        
        collectionView.dataSource = self
        collectionView.delegate = self

    }
    
    // 懒加载控件
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmotionLayout())
    
    private lazy var toolbar: UIToolbar = UIToolbar()
    
    // 视图模型
    private lazy var viewModel = EmoticonViewModel()
   
}

// 设置layout
private class EmotionLayout: UICollectionViewFlowLayout {

    private override func prepareLayout() {
        super.prepareLayout()
    
        let w = collectionView!.bounds.width / 7
        
        let margin = (collectionView!.bounds.height - 3 * w) * 0.499
        
        itemSize = CGSize(width: w, height: w)
        
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        
        sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false

    }
    
}

// 实现数据源方法
extension EmoticonViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return viewModel.packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonViewCellID, forIndexPath: indexPath) as! EmoticonViewCell

        cell.emoticon = viewModel.appendEmoticon(indexPath)
        
        return cell
        
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 传递表情
        selectedEmoticonCallBack(emoticon: viewModel.appendEmoticon(indexPath))
        
    }

}

// 自定义cell
private class EmoticonViewCell: UICollectionViewCell {
    
    var emoticon: Emoticon? {
        didSet {
            
            emoticonBtn.setImage(UIImage(contentsOfFile: (emoticon?.imagePath)!), forState: UIControlState.Normal)
            
            emoticonBtn.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            
            if emoticon!.isRemove {
                
                emoticonBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                
                emoticonBtn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
            
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        emoticonBtn.backgroundColor = UIColor.whiteColor()
        
        contentView.addSubview(emoticonBtn)
        
        emoticonBtn.frame = CGRectInset(bounds, 4, 4)
        
        emoticonBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        // 禁用按钮
        emoticonBtn.userInteractionEnabled = false
    }
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private lazy var emoticonBtn: UIButton = UIButton()
}
